package com.tech.koufu.ui.activity;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.StockJson;
import com.tech.koufu.model.EntrustStock;
import com.tech.koufu.model.StockInfo;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.format.DateFormat;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 
 * @ClassName: EntrustOrCancleActivity
 * @Description: 委托/撤单详情页
 * @author jl_luo
 * @date 2015年3月29日 下午4:37:03
 */
public class EntrustOrCancleActivity extends Activity implements OnClickListener{
	private static final String TAG = "WTDetailActivity";
	private Context mContext;
	private Button btn;
	private TextView tab_stock_name,txt_times;
	private TextView txt_entrust_status,txt_entrust_type;
	private TextView txt_entrust_price,txt_entrust_num;
	private TextView txt_entrust_dealprice,txt_entrust_contract_no;
	
	private RequestQueue mQueue; 
	private MyApplication myApp;
	CookieStringRequest stringRequest;
	private EntrustStock stockInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_entrustorcancle);
		mContext = this;
		initView(); 
		initData();
	}
	
	 @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(mContext);
	}
	 
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(mContext);
	}
	 
	private void initView() {
		((TextView)findViewById(R.id.tv_title)).setText(R.string.top_etrust);
		findViewById(R.id.img_callback).setOnClickListener(this);
		findViewById(R.id.btn_refresh).setVisibility(View.GONE);
		btn = (Button)findViewById(R.id.btn_etrust);
		btn.setOnClickListener(this);
		tab_stock_name = (TextView)findViewById(R.id.tab_stock_name);
		txt_times = (TextView)findViewById(R.id.txt_times);
		
		txt_entrust_status = (TextView)findViewById(R.id.txt_entrust_status);
		txt_entrust_type = (TextView)findViewById(R.id.txt_entrust_type);
		
		txt_entrust_price = (TextView)findViewById(R.id.txt_entrust_price);
		txt_entrust_num = (TextView)findViewById(R.id.txt_entrust_num);
		
		txt_entrust_dealprice = (TextView)findViewById(R.id.txt_entrust_dealprice);
		txt_entrust_contract_no = (TextView)findViewById(R.id.txt_entrust_contract_no);
	}
	
	private void initData(){
		mQueue = Volley.newRequestQueue(getApplicationContext());
		stockInfo = (EntrustStock) getIntent().getSerializableExtra("stockInfo");
		if(stockInfo!=null){
			tab_stock_name.setText(stockInfo.getStockName());  
			txt_times.setText(DateFormat.format(KouFuTools.sdf_date, Calendar.getInstance().getTime())+" "+stockInfo.getTime());
//			txt_entrust_status.setText(String.format(getString(R.string.txt_entrust_status), stockInfo.getStatus()));
			String status = String.format(getResources().getString(R.string.txt_entrust_status), stockInfo.getStatus()); 
			setTextColor(getResources().getColor(R.color.bgBlackColor_63), txt_entrust_status, 0, status.length()-stockInfo.getStatus().length(), status);
//			txt_entrust_type.setText(String.format(getString(R.string.txt_entrust_type), KouFuTools.getEntrustType(stockInfo.entrustBs)));
			String bs = String.format(getString(R.string.txt_entrust_type), KouFuTools.getEntrustType(stockInfo.entrustBs));
			setTextColor(getResources().getColor(R.color.bgBlackColor_63), txt_entrust_type, 0, bs.length()-stockInfo.entrustBs.length()-1, bs);
//			txt_entrust_price.setText(String.format(getString(R.string.txt_entrust_price), stockInfo.getPrice()));
			setTextColor(getResources().getColor(R.color.bgBlackColor_63), txt_entrust_price, 0, 4, String.format(getString(R.string.txt_entrust_price), stockInfo.getPrice()));
//			txt_entrust_num.setText(String.format(getString(R.string.txt_entrust_num), stockInfo.getAmount()));
			setTextColor(getResources().getColor(R.color.bgBlackColor_63), txt_entrust_num, 0, 4, String.format(getString(R.string.txt_entrust_num), stockInfo.getAmount()));
			txt_entrust_dealprice.setText(String.format(getString(R.string.txt_entrust_dealprice), stockInfo.getCjPrice()));
			txt_entrust_contract_no.setText(String.format(getString(R.string.txt_entrust_contract_no), stockInfo.getHtxh()));
			if(stockInfo.getStatus().equals("已成")){
				btn.setVisibility(View.INVISIBLE);
			}
		}
//		postWTRequest();
	}
	
	private void setTextColor(int color,TextView view,int start ,int end,String txt){
		SpannableString style=new SpannableString(txt);           
         style.setSpan(new ForegroundColorSpan(color),start,end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);       
         view.setText(style);  
	}

	 
	
	private void postWTRequest(){
		myApp = (MyApplication) getApplication();
		String url = myApp.url+Statics.Request_WT;
		final String t = KouFuTools.readTimeInfo(new String());
		stringRequest = new CookieStringRequest(Request.Method.POST, url, 
				new Response.Listener<String>() {

					@Override
					public void onResponse(String response) { 
						if(response!=null && !response.equals("")){
							String[] results = response.split(":");
							if(results[0].equals("0")){
								
							}else if (results[0].equals("1")){
								//1:您没有该股票或者卖出数量超出了可卖数，如有异议，请与管理员联系。 
								Toast.makeText(getApplicationContext(), results[1], Toast.LENGTH_SHORT).show();
							}
							Log.d(TAG, "~~~~~~~~~~response~~~~~");
							Log.d(TAG, response);
						} 
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) { 
						
					}
				}){
			@Override
			protected Map<String, String> getParams()
					throws AuthFailureError {    
				Map<String, String> params = new HashMap<String, String>();
				params.put("userid", myApp.getUserid()); 
				params.put("teamid", myApp.getGroupId());  
				params.put("time", t);
				//msg：委托信息，格式：mmlb,stockcode,stockname,stocktype,zqlb,price,amount
				String sid = stockInfo.getStockId();
				String sN = stockInfo.getStockName();
				String msg = new StringBuilder(stockInfo.entrustBs).append(",")
						.append(sid).append(",")
						.append(sN).append(",")
						.append(KouFuTools.getEnCode(sid)).append(",")
						.append(KouFuTools.stockGetZQLB(Integer.parseInt(sid),sN)).append(",")
						.append(stockInfo.price).append(",")
						.append(stockInfo.amount)
						.toString();
				params.put("msg", msg);
				Log.d(TAG, "~~~~~~~~msg=="+msg);
				return params;
			}
						 
		};
		String cookie = KouFuTools.descrypt(myApp.getUserid()+t);
		stringRequest.setHeader(cookie);
		stringRequest.setCharset("GBK");
		stringRequest.setRequestCharset("GBK");
		mQueue.add(stringRequest); 
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_callback:
			this.finish();
			break;
		case R.id.btn_etrust:
			if(stockInfo.getStatus().equals("已成")){
				Toast.makeText(getApplicationContext(), "不能撤单！", Toast.LENGTH_SHORT).show();
			}else{
				postWTRequest();
			}
			break;

		default:
			break;
		}
	}
}
